package com.rcloud.server.sealtalk.service;

import com.alipay.api.domain.Advert;
import com.rcloud.server.sealtalk.constant.Constants;
import com.rcloud.server.sealtalk.controller.param.SendMessageContent;
import com.rcloud.server.sealtalk.dao.UserAdvertisementMapper;
import com.rcloud.server.sealtalk.domain.Friendships;
import com.rcloud.server.sealtalk.domain.Groups;
import com.rcloud.server.sealtalk.domain.UserAdvertisement;
import com.rcloud.server.sealtalk.domain.Users;
import com.rcloud.server.sealtalk.manager.MiscManager;
import com.rcloud.server.sealtalk.rongcloud.RongCloudClient;
import com.rcloud.server.sealtalk.task.NoticeForBackTask;
import com.rcloud.server.sealtalk.task.NoticeForSystemTask;
import com.rcloud.server.sealtalk.util.ImageHandleUtils;
import com.rcloud.server.sealtalk.util.MultiThreadUtils;
import com.rcloud.server.sealtalk.util.N3d;
import io.rong.messages.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;

@Slf4j
@Service
public class UserAdvertisementService extends AbstractBaseService<UserAdvertisement, Integer> {

    @Resource
    private UserAdvertisementMapper mapper;

    @Resource
    private UsersService usersService;

    @Resource
    private FriendshipsService friendshipsService;

    @Resource
    private GroupsService groupsService;

    @Resource
    private MiscManager miscManager;

    @Resource
    private NoticeForBackTask noticeForBackTask;

    @Resource
    private NoticeForSystemTask noticeForSystemTask;

    @Resource
    private ImageHandleUtils imageHandleUtils;

    @Resource
    private MiniWebSocketService miniWebSocketService;

    @Override
    protected Mapper<UserAdvertisement> getMapper() {
        return mapper;
    }

    /**
     * 发送系统消息通知
     */
    public void sendNoticeMsg(Integer currentUserId, String publishNickname, String pushData,
                              String operation, String title, String message, String imageUrl, UserInfo userInfo) {
        log.info("进入发送系统消息通知------APP发布");
        log.info("执行查询全部用户信息------APP发布");
        Example example = new Example(Users.class);
        example.createCriteria().andEqualTo("status", 0);
        List<Users> users = usersService.getByExample(example);
        List<Users> sendArray = new ArrayList<>();
        for (Users user : users) {
            //判断是否是全局接收
            if (user.getAdvertisementOn() == 1) {
                sendArray.add(user);
            } else if (user.getAdvertisementOn() == 2) {
                // 先判断是否是好友
                Friendships friendships1 = friendshipsService.getOneByUserIdAndFriendId(currentUserId, user.getId());
                Friendships friendships2 = friendshipsService.getOneByUserIdAndFriendId(user.getId(), currentUserId);
                if ((friendships1 != null && friendships1.getStatus() == 20) && (friendships2 != null && friendships2.getStatus() == 20)) {
                    sendArray.add(user);
                }
            }
        }
        // 辅助参数  加数
        Map<String, Object> params = new HashMap<>();
        params.put("currentUserId", currentUserId);
        params.put("pushData", pushData);
        params.put("publishNickname", publishNickname);
        // 群组的消息发送

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                log.info("群组GROUPS函数开始执行");
                try {
                    String objectName = Constants.objectName;
                    SendMessageContent content2 = new SendMessageContent();
                    content2.setContent(message);
                    SendMessageContent content3 = new SendMessageContent();
                    List<Groups> groups = groupsService.queryGroups(currentUserId);
                    log.info("执行中------groups的长度" + groups.size());
                    String[] imageArray = new String[0];
                    if (imageUrl != null && !"".equals(imageUrl)) {
                        imageArray = imageUrl.split(",");
                    }
                    for (Groups group : groups) {
                        String targetId = N3d.encode(group.getId());
                        log.info("执行中group------targetId" + targetId);
                        miscManager.sendTaskGroupMessageTxt(currentUserId, objectName, content2, title, targetId, userInfo);
                        //判断图片信息
                        if (imageArray.length > 0) {
                            for (String url : imageArray) {
                                content3.setContent(imageHandleUtils.getImageEncodeBase64(url, 240));
                                log.info("图片原路径信息:{}", url);
                                content3.setImageUri(imageHandleUtils.uploadFile(url));
                                miscManager.sendTaskGroupMessageImage(currentUserId, objectName, content3, title, targetId, userInfo);
                            }
                        }
                    }
                    //执行发送websocket的消息通知
                    UserAdvertisement advertisement = new UserAdvertisement();
                    advertisement.setUserNickname(userInfo.getName());
                    advertisement.setUserAvatar(userInfo.getIcon());
                    advertisement.setTitle(title);
                    advertisement.setContent(message);
                    advertisement.setImageUrl(imageUrl);
                    miniWebSocketService.userJoinTask(advertisement);
                } catch (Exception e) {
                    log.info("群组消息发送失败" + e);
                }
                log.info("群组GROUPS函数执行结束");
            }
        });
        thread.start();
        // 执行多线程处理，并返回处理结果
        //判断需要用几个线程处理
        int threadCount = users.size() / 1000;
        // 创建多线程处理任务
        MultiThreadUtils<Users> threadUtils = MultiThreadUtils.newInstance(threadCount + 1);
        // 执行多线程处理，并返回处理结果
        threadUtils.execute(users, params, noticeForSystemTask);
    }


    /**
     * 发送系统消息通知
     */
    public void sendNoticeMsgForInterface(String publishNickname, String pushData) {
        log.info("进入发送系统消息通知------后台发布");
        log.info("执行查询全部用户信息------后台发布");
        Example example = new Example(Users.class);
        example.createCriteria().andEqualTo("status", 0);
        List<Users> users = usersService.getByExample(example);
        // 辅助参数  加数
        Map<String, Object> params = new HashMap<>();
        params.put("pushData", pushData);
        params.put("publishNickname", publishNickname);
        // 执行多线程处理，并返回处理结果
        threadHandle(users, params);
    }


    private void threadHandle(List<Users> users, Map<String, Object> params) {
        //判断需要用几个线程处理
        int threadCount = users.size() / 1000;
        // 创建多线程处理任务
        MultiThreadUtils<Users> threadUtils = MultiThreadUtils.newInstance(threadCount + 1);
        // 执行多线程处理，并返回处理结果
        threadUtils.execute(users, params, noticeForBackTask);
    }


    public void updateIsTopAdvertisement(Integer advertisementId) {
        mapper.updateIsTopAdvertisement(advertisementId);
    }

    public UserAdvertisement queryRandomAdvertisement() {
        return mapper.queryRandomAdvertisement();
    }
}
